<script setup>
import { ref } from 'vue'

const props = defineProps(['node'])
const emit = defineEmits(['file-selected'])

const isOpen = ref(false)

const pathApi = window.electronAPI.path;

const toggle = async () => {
  if (props.node.isDirectory) {
    if (!props.node.children.length) {
      console.log('children===========', props.node)
      if (!props.node.path) {
        return
      }
      const children = await window.electronAPI.readDir(props.node.path);
      props.node.children = children.map(file => ({
        name: file.name,
        path: pathApi.join(props.node.path, file.name),
        isDirectory: file.isDirectory,
        children: file.isDirectory ? [] : null
      }))
    }
    isOpen.value = !isOpen.value
  } else {
    emit('file-selected', props.node.path)
  }
}
</script>

<template>
  <li>
    <div class="node-item" @click="toggle">
      <span v-if="node.isDirectory">{{ isOpen ? '📂' : '📁' }}</span>
      <span v-else>📄</span>
      {{ node.name }}
    </div>
    <ul v-show="isOpen && node.children" v-if="node.isDirectory">
      <TreeNode
        v-for="child in node.children"
        :key="child.path"
        :node="child"
        @file-selected="(path) => emit('file-selected', path)"
      />
    </ul>
  </li>
</template>

<style scoped>
.node-item {
  /*padding: 4px 8px;*/
  cursor: pointer;
  user-select: none;
}

.node-item:hover {
  background-color: #f5f5f5;
}
</style>
